//
//  MyInfoViewController.m
//  TuanZhongTuan
//
//  Created by zinrro on 2017/3/18.
//  Copyright © 2017年 yaoqi yaoqi. All rights reserved.
//

#import "MyInfoViewController.h"
#import "MyInfoTableViewCell.h"
#import "MyInfoAvatarTableViewCell.h"
#import "MyInfoDetailsTableViewCell.h"
#import "PickerChoiceView.h"

#import "RegisterViewController.h"

//#import "SetPayPasswordViewController.h"//修改密码

@interface MyInfoViewController ()<UITableViewDataSource, UITableViewDelegate, TFPickerDelegate, UIImagePickerControllerDelegate,UINavigationControllerDelegate,UIActionSheetDelegate>
{
    NSString *address;
    NSIndexPath *sexIndexPath;
    NSString *nameStr;
}
@property (nonatomic, strong) UITableView           *myTableView;
@property (nonatomic, strong) NSMutableArray        *regionIdMuArray;
@property (nonatomic, strong) NSDictionary          *data;
@property (nonatomic, strong) UITableView           *bottomTableView;
@property (nonatomic, strong) NSArray               *sexs;
@end

@implementation MyInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor =[UIColor whiteColor];
    [self setNavTitleText:@"设置"];
   
    [self initTableView];
    [self initBottomView];
    self.sexs = @[@"男",@"女",@"取消"];
    address = @"";
}
-(void)initBottomView{
    UIButton *addAddressBtn = [[UIButton alloc]initWithFrame:CGRectMake(50,KScreenHeight - Height_Indicator - 44 - 60 , KScreenWidth - 100,44)];
    
    [addAddressBtn.layer addSublayer:[self setButtonLayer:addAddressBtn]];
    [addAddressBtn setTitle:@"保存" forState:0];
    [addAddressBtn setTitleColor:[UIColor whiteColor] forState:0];
    addAddressBtn.titleLabel.font = BoldFont(18);
    addAddressBtn.layer.cornerRadius = 22;
    addAddressBtn.layer.masksToBounds = YES;
    [addAddressBtn addTarget:self action:@selector(saveCellMessage) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addAddressBtn];
}



-(void)initTableView
{
    
    self.myTableView = [[UITableView alloc]initWithFrame:CGRectMake(0, Height_NavBar, KScreenWidth, KScreenHeight - Height_NavBar - Height_Indicator - 60 - 50) style:UITableViewStyleGrouped];
//    self.myTableView.separatorInset = UIEdgeInsetsMake(0, 0, 0, 0);
//    self.myTableView.separatorColor = [UIColor groupTableViewBackgroundColor];
    self.myTableView.backgroundColor = [UIColor whiteColor];
    self.myTableView.dataSource = self;
    self.myTableView.delegate = self;
    self.myTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(MyInfoHeaderRefresh)];
    [self.myTableView.mj_header beginRefreshing];
    [self.view addSubview:self.myTableView];
}

#pragma mark - UITableViewDataSource



-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;

}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        return 55;
    }
    return 44;
}
-(UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    
    UIView * view =[[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 100)];
    return view;
    
}
-(UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    UIView *bgV = [[UIView alloc]initWithFrame:CGRectMake(0, 0, KScreenWidth, 54)];
    return bgV;
    
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 0.001f;
}
-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
     return 0.00001f;
}



- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0) {
        //头像
        static NSString *ID = @"portrait";
        MyInfoAvatarTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if(!cell){
            cell = [[MyInfoAvatarTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        if (![self.data[@"portrait"] isEqualToString:@""]) {
//            [cell.avatarImageView sd_setImageWithURL:[NSURL URLWithString:self.data[@"portrait"]] placeholderImage:[UIImage imageNamed:@"bg_grzx"]];
        }else{
             cell.avatarImageView.image = [UIImage imageNamed:@"myself_img_20"];
        }
        cell.avatarImageView.image = [UIImage imageNamed:@"myself_img_20"];
        return cell;
    }else if (indexPath.row == 2){
        //性别
        static NSString *ID = @"sex";
        MyInfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
        if(!cell){
            cell = [[MyInfoTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
        }
        cell.leftLabel.text = @"性别";
        cell.leftLabel.frame = CGRectMake(15, 11, 50, 20);
        if ([[self.data objectForKey:@"sex"] intValue] == 1) {
            cell.rightLabel.text = @"男";
        } else if ([[self.data objectForKey:@"sex"] intValue] == 2) {
            cell.rightLabel.text = @"女";
        }
        cell.rightLabel.frame = CGRectMake(60, 11, KScreenWidth-60 - 40, 20);
        return cell;
        
    }
    //姓名
    static NSString *ID = @"name";
    MyInfoDetailsTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID];
    if(!cell){
        cell = [[MyInfoDetailsTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
    }
    //10, 20, 80, 20
    cell.titleLabel.text = @"姓名";
    cell.titleLabel.frame = CGRectMake(15, 11, 50, 20);
    if (![[self.data objectForKey:@"nickName"] isEqualToString:@""]) {
        nameStr = [self.data objectForKey:@"nickName"];
        cell.contentTextField.text = [self.data objectForKey:@"nickName"];
    }else{
        nameStr = [self.data objectForKey:@"username"];
        cell.contentTextField.text = [self.data objectForKey:@"username"];
    }
    cell.contentTextField.frame = CGRectMake(60, 11, KScreenWidth- 60 - 40 , 20);
    [cell.contentTextField addTarget:self action:@selector(editorName:) forControlEvents:UIControlEventEditingDidEnd];
    return cell;
    
}

#pragma mark - 选中某行
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0) {
        //修改图像
        [self modifyAvatarAlter];
    }else if (indexPath.row == 2){
        //修改性别
      sexIndexPath = [NSIndexPath indexPathForRow:indexPath.row inSection:0];
        UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"性别选择" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"男",@"女", nil];
        sheet.actionSheetStyle = UIActionSheetStyleDefault;
        
        [sheet showInView:tableView];
        
    }
}
- (void)PickerSelectorIndexString:(NSString *)str {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:3 inSection:0];
    MyInfoTableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
    cell.rightLabel.text = str;
    NSLog(@"日期选择器 = %@",str);
    [self commitEditorInfo:str andPara:@"birthdayStr"];
}
#pragma mark- 头像
-(void)modifyAvatarAlter
{
    /**
     *  弹出提示框
     */
    //初始化提示框
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    //按钮：从相册选择，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        //初始化UIImagePickerController
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式1：通过相册（呈现全部相册），UIImagePickerControllerSourceTypePhotoLibrary
        //获取方式2，通过相机，UIImagePickerControllerSourceTypeCamera
        //获取方法3，通过相册（呈现全部图片），UIImagePickerControllerSourceTypeSavedPhotosAlbum
        PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //允许编辑，即放大裁剪
        PickerImage.allowsEditing = YES;
        //自代理
        PickerImage.delegate = self;
        //页面跳转
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮：拍照，类型：UIAlertActionStyleDefault
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
        /**
         其实和从相册选择一样，只是获取方式不同，前面是通过相册，而现在，我们要通过相机的方式
         */
        UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init];
        //获取方式:通过相机
        PickerImage.sourceType = UIImagePickerControllerSourceTypeCamera;
        PickerImage.allowsEditing = YES;
        PickerImage.delegate = self;
        [self presentViewController:PickerImage animated:YES completion:nil];
    }]];
    //按钮：取消，类型：UIAlertActionStyleCancel
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - UIImagePickerControllerDelegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info{
    //定义一个newPhoto，用来存放我们选择的图片
    UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"];
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    //上传图片
    [self showHUDWithString:@"头像上传中,请稍后"];
    [ZWJNetworkManager uloadImage:newPhoto WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
        if ([dic[Code] intValue] == 200) {
            NSLog(@"上传图片成功");
            NSMutableDictionary *parameterDict = [NSMutableDictionary dictionary];
            NSString *showUrlStr = dic[Response][@"showUrl"];
            NSLog(@"%@",showUrlStr);
            [parameterDict setObject:dic[Response][@"url"] forKey:@"imgUrl"];
            [ZWJNetworkManager requestWithRequestData:parameterDict WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
                if ([[dic objectForKey:Code] intValue] == 200) {
                    [self showWithTitle:@"修改头像成功"];
                    NSURL *url = [NSURL URLWithString:showUrlStr];
                    MyInfoAvatarTableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
//                    [cell.avatarImageView sd_setImageWithURL:url];
                    
                }else{
                   [self showWithTitle:dic[Response]];
                }
                
            } failure:^(id error) {
                [self showWithTitle:@"修改头像失败"];
            }];
        }
    } failure:^(id error) {
         [self showWithTitle:@"头像上传失败"];
    }];
    [self dismissViewControllerAnimated:YES completion:nil];
    [self.myTableView reloadRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationNone];
}
- (void)MyInfoHeaderRefresh {
    [ZWJNetworkManager requestWithRequestData:nil WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
        [self->_myTableView.mj_header endRefreshing];
        if ([dic[Code] intValue] == 200) {
            self.data = dic[Response];
            [self->_myTableView reloadData];
        }
    } failure:^(id error) {
        [self->_myTableView.mj_header endRefreshing];
    }];
}
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    MyInfoTableViewCell *cell = [self.myTableView cellForRowAtIndexPath:sexIndexPath];
    NSString *sex = nil;
    switch (buttonIndex) {
        case 0:
            cell.rightLabel.text = @"男";
            sex = @"1";
            break;
        case 1:
            cell.rightLabel.text = @"女";
            sex = @"2";
            break;
        default:
            break;
    }
    if (buttonIndex == 0 || buttonIndex == 1) {
        [self commitEditorInfo:sex andPara:@"sex"];
    }
    
}

#pragma mark- 修改昵称
-(void)editorName:(UITextField *)sender{
    if (![sender.text isEqualToString:nameStr]) {
        nameStr = sender.text;
        [self commitEditorInfo:sender.text andPara:@"nickName"];
    }
    
}
-(void)commitEditorInfo:(NSString *)str andPara:(NSString *)paraStr{
    [ZWJNetworkManager requestWithRequestData:@{paraStr:str} WithUrl:@"" WithWithCompletionBlockWithSuccess:^(NSDictionary *dic) {
        if ([dic[Code] intValue] == 200) {
            [self showWithTitle:@"更新成功"];
        }
    } failure:^(id error) {
        [self showWithTitle:@"更新失败"];
    }];
}
-(CAGradientLayer *)setButtonLayer:(UIView *)view{
    CAGradientLayer *gradientLayer0 = [[CAGradientLayer alloc] init];
    gradientLayer0.frame = view.bounds;
    gradientLayer0.colors = @[
                              (id)[UIColor colorWithRed:255.0f/255.0f green:177.0f/255.0f blue:26.0f/255.0f alpha:1.0f].CGColor,
                              (id)[UIColor colorWithRed:255.0f/255.0f green:108.0f/255.0f blue:0.0f/255.0f alpha:1.0f].CGColor,
                              (id)[UIColor colorWithRed:255.0f/255.0f green:87.0f/255.0f blue:0.0f/255.0f alpha:1.0f].CGColor,
                              (id)[UIColor colorWithRed:255.0f/255.0f green:66.0f/255.0f blue:0.0f/255.0f alpha:1.0f].CGColor];
    gradientLayer0.locations = @[@0, @1, @1, @1];
    [gradientLayer0 setStartPoint:CGPointMake(0, 1)];
    [gradientLayer0 setEndPoint:CGPointMake(1, 1)];
    return gradientLayer0;
}

-(void)saveCellMessage{
    
}
@end
